import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/back_button_widget.dart';
import 'package:webview_flutter/webview_flutter.dart';

/// 显示h5页面组件
class HiWebViewWidget extends StatefulWidget {
  /// h5页面url
  final String url;

  /// 自定义标题
  final String title;

  /// 返回按钮显示什么样式
  final bool showClose;

  /// 返回按钮距离边界的距离
  final double? btnPadding;

  const HiWebViewWidget({
    super.key,
    required this.url,
    required this.title,
    this.showClose = true,
    this.btnPadding,
  });

  @override
  State<HiWebViewWidget> createState() => _HiWebViewWidgetState();
}

class _HiWebViewWidgetState extends State<HiWebViewWidget> {
  /// 方便在initState里面初始化
  late String url;

  /// 控制器
  late WebViewController controller;

  @override
  void initState() {
    super.initState();
    url = widget.url;
    _initWebViewController();
  }

  @override
  void dispose() {
    super.dispose();
    controller.clearLocalStorage();
  }

  @override
  Widget build(BuildContext context) {
    // 处理 Android 物理返回键，返回 H5 的上一页
    // https://docs.flutter.dev/release/breaking-changes/android-predictive-back
    return PopScope(
      canPop: false, // 手动接管返回任务
      onPopInvoked: (bool didPop) async {
        // 是否可以返回上一页
        if (await controller.canGoBack()) {
          // 返回H5的上一页
          controller.goBack();
        } else {
          // 判断页面是在装载之后
          // if (context.mounted) {
          //   debugPrint("手动接管返回任务执行 ===> ");
          //   NavigatorUtil.pop(context);
          // }
        }
      },
      child: Scaffold(
        body: Column(
          children: [
            _appBar(context),
            Expanded(child: WebViewWidget(controller: controller)),
          ],
        ),
      ),
    );
  }

  /// 初始化webView控制器方法
  void _initWebViewController() {
    controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(colorWhite1)
      ..setNavigationDelegate(NavigationDelegate())
      ..loadRequest(Uri.parse(url));
  }

  /// 标题组件
  _appBar(BuildContext context) {
    // 获取安全边距
    var top = ScreenUtil().statusBarHeight;
    return Container(
      height: 88,
      margin: EdgeInsets.only(top: top),
      padding: EdgeInsets.symmetric(horizontal: widget.btnPadding ?? 16),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          widget.showClose
              ? BackButtonWidget.close(pageContext: context,size: 18,)
              : BackButtonWidget.back(pageContext: context,size: 18,),
          Text(
            widget.title,
            style: FontUtil.fontBlack1(18, fontWeight: FontWeight.w500),
          ),
          // 右边占位使用
          SizedBox(
            height: 48,
            width: 48,
          ),
        ],
      ),
    );
  }
}
